﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraScheduler;
using System.Data.SqlClient;
using Gem_Tools_Utility;
using Gem_Tools_Entity.Gem_Tools;
using Gem_Tools_Controller.Gem_Tools;
using GE_Management_Tool.Planning;
using GE_Management_Tool;
using DevExpress.XtraTreeList.Nodes;
using GE_Management_Tool.Planning.UserControl;
using DevExpress.XtraTreeList.Columns;
using System.Linq;
using DevExpress.XtraScheduler.Native;
using DevExpress.XtraScheduler.Drawing;
using DevExpress.XtraTreeList;
using GE_Management_Tool.Reporting;
using DevExpress.XtraReports.UI;

namespace Gem_Tools.Planning.UserControl
{
    public partial class ucA001_Project_Schedule : DevExpress.XtraEditors.XtraUserControl
    {
        IList<CProject_Group> m_lsProject_Group;
        IList<CAsset> m_lsAsset;
        CAsset m_objSelected_Asset;
        CProject m_objProject;
        IList<CTasks> m_lsTasks;
        //--------------------------
        IList<CProject_Staff> m_lsProject_Staff;
        IList<CProject_Staff> m_lsProject_Manager;
        CProject_Staff m_objSelected;
        IList<CStaff> m_lsStaff;
        IList<CStaff> m_lsManager;
        CProject_Staff m_objSelectedManager;
        IDictionary<int, int> m_dicRegency;


        private void Init_Data(CProject p_objProject)
        {
            //---------------------------------------------------------------------
            //Load Project Info:

            lbProject_Name.Text = p_objProject.Name;
            txtStartDate.Text = m_objProject.Start_Date.ToString("dd-MMM-yyyy");
            txtEndDate.Text = p_objProject.End_Date.ToString("dd-MMM-yyyy");
            txtManday.Text = p_objProject.Manday.ToString("n0");
            txtNote.Text = p_objProject.Note;

            CClient_Controller v_ctrlClient = new CClient_Controller();
            CClient v_objClient = v_ctrlClient.Get_Client_By_ID(p_objProject.Client_ID);
            txtClient_Name.Text = v_objClient.Client_Name;

            Init_Tasks(p_objProject);

            //sau khi Assign Task mình sẽ kiểm tra xem task nào đã được assign thì thể hiện dấu check cảnh báo đã được Assign:
            foreach (CAsset v_asset in m_lsAsset)
            {
                foreach (CTasks v_Task in m_lsTasks)
                {
                    if (v_asset.Auto_ID == v_Task.Asset_ID)
                    {
                        v_asset.is_Assign = true;
                        v_asset.Note = v_Task.Full_Name;
                    }
                }
            }


        }

        private void Init_Tasks(CProject p_objProject)
        {
            m_lsTasks = new List<CTasks>();
            CTasks_Controller v_objCtrlTasks = new CTasks_Controller();
            if (p_objProject.is_Active > 0)
            {
                m_lsTasks = v_objCtrlTasks.A001_sp_sel_List_Tasks_By_Project_ID(CConfig.g_intGem_Tools_Current_Project);
            }
        }

        public ucA001_Project_Schedule()
        {
            InitializeComponent();
            CCommon_Function.Format_All(this);
            this.grvProject_Staff.OptionsBehavior.Editable = true;
            this.grvProject_Manager.OptionsBehavior.Editable = true;
        }

        private void Load_Project_Staff()
        {
            //Load Project Staff Information:
            m_lsProject_Staff = new List<CProject_Staff>();
            CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
            m_lsProject_Staff = v_ctrlStaff.A001_List_Project_Staff_By_Project_ID_And_Regency_ID(CConfig.g_intGem_Tools_Current_Project,
                                                                                                CUtility.Convert_To_Int32(EStaff_Type.Artist));
            cProjectStaffBindingSource.DataSource = m_lsProject_Staff;
        }

        private void ucA001_Project_Schedule_Load(object sender, EventArgs e)
        {
            try
            {
                CProject_Controller v_ctrlProject = new CProject_Controller();
                m_objProject = v_ctrlProject.Get_Project_By_ID(CConfig.g_intGem_Tools_Current_Project);
                if (m_objProject.is_Active > 0 && CSession.Active_Staff.Regency != "Admin")
                {
                    pActiveProject.Enabled = false;
                }

                Load_Project_Staff();

                CProject_Group_Controller v_ctrlGroup = new CProject_Group_Controller();
                m_lsProject_Group = v_ctrlGroup.A001_List_Project_Group_By_Project_ID(CConfig.g_intGem_Tools_Current_Project);

                m_lsAsset = new List<CAsset>();
                CAsset_Controller v_ctrlAsset = new CAsset_Controller();
                m_lsAsset = v_ctrlAsset.A001_List_Asset_By_Project_ID(CConfig.g_intGem_Tools_Current_Project);

                foreach (CProject_Group v_obj in m_lsProject_Group)
                {
                    CAsset v_tmp = new CAsset();
                    v_tmp.Auto_ID = v_obj.Auto_ID * -1;
                    v_tmp.Name = v_obj.Group_Name;
                    v_tmp.Group_ID = 0;
                    m_lsAsset.Add(v_tmp);
                }
                Init_Tasks(m_objProject);
                Init_Data(m_objProject);
                
                trvAsset.DataSource = m_lsAsset;
                Set_Image_Icon();


                //----------------------------------------------------------------------
                m_lsStaff = new List<CStaff>();
                CStaff_Controller v_objCtrlStaff = new CStaff_Controller();
                m_lsStaff = v_objCtrlStaff.A001_sp_sel_List_Staff_By_Regency_ID(CUtility.Convert_To_Int32(EStaff_Type.Artist));
                lkeStaff.DataSource = m_lsStaff;
                lkeProject_STaff.DataSource = m_lsStaff;
                //----------------------------------------------------------------------
                Set_Image_Icon();

                //cập nhật ngày 18-dec-2013
                m_lsManager = new List<CStaff>();
                m_lsManager = v_objCtrlStaff.A001_sp_sel_List_Producer_Technician();
                lkeManager.DataSource = m_lsManager;
                m_dicRegency = new Dictionary<int, int>();

                foreach (CStaff v_obj in m_lsManager)
                {
                    m_dicRegency.Add(v_obj.Auto_ID, v_obj.Regency_ID);
                }

                m_lsProject_Manager = new List<CProject_Staff>();
                CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                m_lsProject_Manager = v_ctrlStaff.A001_sp_sel_List_Pro_Tech_Art_By_Project_ID(CConfig.g_intGem_Tools_Current_Project);
                cProjectStaffBindingSource1.DataSource = m_lsProject_Manager;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void Set_Image_Icon()
        {
            foreach (TreeListNode v_Node in trvAsset.Nodes)
            {
                string v_Str = v_Node.GetValue("Auto_ID").ToString();
                if (int.Parse(v_Str) < 0)
                {
                    v_Node.StateImageIndex = 0;
                    foreach (TreeListNode v_child in v_Node.Nodes)
                    {
                        v_child.StateImageIndex = 1;
                    }
                }
            }
        }

        private void btnProjectBatch_Click(object sender, EventArgs e)
        {
            try
            {
                frmA0012_Project_Group v_frm = new frmA0012_Project_Group();
                v_frm.ShowDialog();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void btnAdd_Asset_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_objSelected_Asset != null)
                {
                    if (m_objSelected_Asset.Auto_ID < 0)
                    {
                        frmA0013_Asset v_frm = new frmA0013_Asset();
                        v_frm.Show_To_Display(CConfig.g_intGem_Tools_Current_Project, m_objSelected_Asset.Auto_ID, m_objSelected_Asset.Name);
                        ucA001_Project_Schedule_Load(null, null);
                    }
                    else
                    {
                        throw new Exception("- Please select 1 batch or group.");
                    }
                }
                else
                {
                    throw new Exception("- Please select 1 batch or group.");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            try
            {
                m_objSelected_Asset = (CAsset)trvAsset.GetDataRecordByNode(trvAsset.FocusedNode);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        public void Proccess_Key_Down(Boolean is_Batch)
        {
            if (is_Batch == true)
            {
                btnProjectBatch_Click(null, null);
            }
            else
            {
                btnAdd_Asset_Click(null, null);
            }
        }

        private void btnEditProject_Click(object sender, EventArgs e)
        {
            try
            {
                frmA0011_Project_Edit_Page v_frm = new frmA0011_Project_Edit_Page();

                Boolean v_boolean = false;
                m_objProject = v_frm.Show_To_Edit(m_objProject, ref v_boolean);
                Init_Data(m_objProject);

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void trvTasks_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            try
            {
                //m_objSelected_Tasks = (CTasks)trvTasks.GetDataRecordByNode(trvTasks.FocusedNode);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void treeList1_FilterNode(object sender, DevExpress.XtraTreeList.FilterNodeEventArgs e)
        {
            if (CUtility.Convert_To_Bool(e.Node["is_Assign"]) == true)
            {
                if (chkShow_All_Asset.Checked == false)
                {
                    e.Node.Visible = false;
                }
                else
                {
                    e.Node.Visible = true;
                }
                e.Handled = true;
            }

            //List<TreeListColumn> filteredColumns = e.Node.TreeList.Columns.Cast<TreeListColumn>(
            //    ).Where(c => c.FilterInfo.AutoFilterRowValue != null).ToList();
            //if (filteredColumns.Count == 0) return;
            //e.Handled = true;
            //e.Node.Visible = filteredColumns.Any(c => IsNodeMatchFilter(e.Node, c));


        }

        static bool IsNodeMatchFilter(TreeListNode node, TreeListColumn column)
        {
            string filterValue = column.FilterInfo.AutoFilterRowValue.ToString();
            if (node.GetDisplayText(column).StartsWith(filterValue)) return true;
            foreach (TreeListNode n in node.Nodes)
                if (IsNodeMatchFilter(n, column)) return true;
            return false;
        }

        private string Check_Data()
        {
            StringBuilder v_Sb = new StringBuilder();
            if (m_objSelected.Staff_ID < 0)
            {
                v_Sb.AppendLine("Missing Staff Name.");
            }

            return v_Sb.ToString();
        }

        private void grvProject_Staff_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            try
            {
                m_objSelected.Project_ID = CConfig.g_intGem_Tools_Current_Project;
                string error = Check_Data();
                if (error != "")
                {
                    throw new Exception(error);
                }
                //lúc này là mới thêm vào cho nên Auto ID  = 0;
                if (m_objSelected.Auto_ID <= 0)
                {
                    CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                    m_objSelected.Auto_ID = v_ctrlStaff.Insert_Project_Staff(m_objSelected);
                    XtraMessageBox.Show("Insert Success !");
                }
                else
                {
                    // ở đây là thêm vào hệ thống tự sinh ra auto_id rồi nên auto_id chắc chắn > 0;
                    CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                    v_ctrlStaff.Update_Project_Staff(m_objSelected);
                    if (checkEdit1.Checked == false)
                    {
                        XtraMessageBox.Show("Update Success !");
                    }
                }


            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void grvProject_Staff_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (e.Button.ButtonType == NavigatorButtonType.Remove)
            {
                    e.Handled = true;
                    if (XtraMessageBox.Show("Are you sure you want to delete these rows ?", "Warning", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                    {
                        for (int v_i = 0; v_i < m_lsProject_Staff.Count; v_i++)
                        {
                            if (m_lsProject_Staff[v_i].Selected == true)
                            {
                                CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                                v_ctrlStaff.Delete_Project_Staff(m_lsProject_Staff[v_i].Auto_ID, CSession.Active_User_Name);
                                m_lsProject_Staff.Remove(m_lsProject_Staff[v_i]);
                                v_i--;
                            }
                        }
                    }
                grdProject_Staff.RefreshDataSource();
            }
        }

        private void grvProject_Staff_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                m_objSelected = (CProject_Staff)grvProject_Staff.GetRow(grvProject_Staff.FocusedRowHandle);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            try
            {
                if (e.Node.ParentNode != null)
                {
                    if (e.Node.Checked == false)
                    {
                        e.Node.ParentNode.Checked = false;
                    }
                    else
                    {
                        e.Node.ParentNode.Checked = true;
                        foreach (TreeListNode node in e.Node.ParentNode.Nodes)
                        {
                            if (node.Checked == false)
                            {
                                e.Node.ParentNode.Checked = false;
                            }
                        }
                    }
                }

                if (e.Node.Nodes.Count > 0)
                {
                    /* Calls the CheckAllChildNodes method, passing in the current 
                    Checked value of the TreeNode whose checked state changed. */
                    CheckAllChildNodes(e.Node, e.Node.Checked);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK); ;
            }
        }

        private void CheckAllChildNodes(TreeListNode treeNode, bool nodeChecked)
        {
            foreach (TreeListNode node in treeNode.Nodes)
            {
                if (CUtility.Convert_To_Bool(node["is_Assign"]) == false)
                    node.Checked = nodeChecked;
                if (node.Nodes.Count > 0)
                {
                    // If the current node has child nodes, call the CheckAllChildsNodes method recursively. 
                    this.CheckAllChildNodes(node, nodeChecked);
                }
            }
        }

        private void chkShow_All_Asset_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                trvAsset.FilterNodes();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void grdStaff_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {

        }

        private void grvProject_Manager_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                m_objSelectedManager = (CProject_Staff)grvProject_Manager.GetRow(grvProject_Manager.FocusedRowHandle);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private string Check_Data_Manager()
        {
            StringBuilder v_Sb = new StringBuilder();
            if (m_objSelectedManager.Staff_ID <= 0)
            {
                v_Sb.AppendLine("Missing Staff Name.");
            }

            return v_Sb.ToString();
        }

        private void grvProject_Manager_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            try
            {
                m_objSelectedManager.Project_ID = CConfig.g_intGem_Tools_Current_Project;
                string error = Check_Data_Manager();
                if (error != "")
                {
                    throw new Exception(error);
                }

                int p_iRegency_id = 0;
                m_dicRegency.TryGetValue(m_objSelectedManager.Staff_ID, out p_iRegency_id);
                m_objSelectedManager.Regency_ID = p_iRegency_id;

                //lúc này là mới thêm vào cho nên Auto ID  = 0;
                if (m_objSelectedManager.Auto_ID <= 0)
                {
                    CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                    m_objSelectedManager.Auto_ID = v_ctrlStaff.Insert_Project_Staff(m_objSelectedManager);
                    XtraMessageBox.Show("Insert Success !");
                }
                else
                {
                    // ở đây là thêm vào hệ thống tự sinh ra auto_id rồi nên auto_id chắc chắn > 0;
                    CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                    v_ctrlStaff.Update_Project_Staff(m_objSelectedManager);
                    XtraMessageBox.Show("Update Success !");
                }

                grdProject_Manager.RefreshDataSource();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void grdProject_Manager_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (e.Button.ButtonType == NavigatorButtonType.Remove)
            {
                e.Handled = true;
                if (XtraMessageBox.Show("Are you sure you want to delete this row ?", "Warning", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    CProject_Staff_Controller v_ctrlStaff = new CProject_Staff_Controller();
                    v_ctrlStaff.Delete_Project_Staff(m_objSelectedManager.Auto_ID, CSession.Active_User_Name);
                    this.m_lsProject_Manager.Remove(m_objSelectedManager);
                    grdProject_Manager.RefreshDataSource();
                }
            }
        }

        private void btnAssign_tasks_To_Artist_Click(object sender, EventArgs e)
        {
            try
            {
                frmA0019_Add_Multiple_Artists v_frm = new frmA0019_Add_Multiple_Artists();
                v_frm.ShowDialog();
                Load_Project_Staff();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkEdit1.Checked == true)
            {
                grdProject_Staff.EmbeddedNavigator.Buttons.Append.Visible = false;
                grdProject_Staff.EmbeddedNavigator.Buttons.Edit.Visible = false;
                colFull_Name.OptionsColumn.ReadOnly = true;
                lkeProject_STaff.ReadOnly = true;
            }
            else
            {
                grdProject_Staff.EmbeddedNavigator.Buttons.Append.Visible = true;
                grdProject_Staff.EmbeddedNavigator.Buttons.Edit.Visible = true;
                colFull_Name.OptionsColumn.ReadOnly = false;
                lkeProject_STaff.ReadOnly = false;
            }
        }
    }
}
